package com.wxlsoft.ui.conflist;

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;

import com.wxlsoft.config.ConfigImportHandler;
import com.wxlsoft.config.model.EsbAppInfo;
import com.wxlsoft.config.model.EsbProtocol;
import com.wxlsoft.config.model.EsbPublishSelect;
import com.wxlsoft.config.model.EsbServiceFlow;
import com.wxlsoft.config.model.EsbServiceidentify;
import com.wxlsoft.ui.ShowErrorMessage;
import com.wxlsoft.utils.LogUtils;

public class ModePanel extends JPanel implements ActionListener {

	private ExecutorService pool = Executors.newFixedThreadPool(1);
	
	private static final long serialVersionUID = 1L;

	private final ConfigImportHandler importHandler;

	private JComboBox<String> jcomAppId;

	private JComboBox<String> jcomInProtocal;

	private JComboBox<String> jcomOutProtocal;
	
	private JComboBox<String> jcomFlows;

	public ModePanel(ConfigImportHandler importHandler) {
		this.importHandler = importHandler;
		this.jcomAppId = new JComboBox<>(new String[] {"选择应用ID..."});
		this.jcomAppId.addMouseListener(new EsbListener(MouseType.APPID));
		this.jcomInProtocal = new JComboBox<>(new String[] {"选择接入协议..."});
		this.jcomInProtocal.addMouseListener(new EsbListener(MouseType.PROTOCAL));
		this.jcomOutProtocal = new JComboBox<>(new String[] {"选择接出协议..."});
		this.jcomOutProtocal.addMouseListener(new EsbListener(MouseType.SERVICEDEFINED));
		this.jcomFlows = new JComboBox<>(new String[] {"选择适配流程..."});
		this.jcomFlows.addMouseListener(new EsbListener(MouseType.FLOWS));
		
		
		setLayout(new GridLayout(6, 1));
		add(jcomAppId);
		add(jcomInProtocal);
		add(jcomOutProtocal);
		add(jcomFlows);
		
		add(new JLabel("TIPS：切换appId时，请手动点击重置参数"));
		JButton jButton = new JButton("重置参数");
		jButton.addActionListener(new EsbListener(MouseType.CHANGEAPPID));
		add(jButton);
	}
	
		
	class EsbListener extends MouseAdapter implements ActionListener {
		
		public MouseType type;

		public EsbListener(MouseType type) {
			this.type = type;
		}
		
		@Override
		public void mousePressed(MouseEvent e) {
			pool.execute(() -> {
				switch (type) {
					case APPID: queryAppid();
						break;
					case PROTOCAL: queryInProtocal();
						break;
					case SERVICEDEFINED: queryOutProtocal();
						break;
					case FLOWS: queryFlows();
						break;
					default:
						break;
				}
			});
		}

		private void queryAppid() {
			if (fill(jcomAppId)) {
				try {
					List<EsbAppInfo> appids = importHandler.getPlatform().queryAppIds();
					if (appids.isEmpty()) {
						ShowErrorMessage.show(String.format("请到控制台配置应用"));
						return;
					}
					
					jcomAppId.removeAllItems();
					for (int i = 0, len = appids.size(); i < len; i++) {
						EsbAppInfo appInfo = appids.get(i);
						jcomAppId.insertItemAt(appInfo.getServiceName(), i);
					}
				} catch (Exception e1) {
					LogUtils.error(e1.getMessage(), e1);
				}
			}
		}

		private void queryInProtocal() {
			if (fill(jcomInProtocal)) {
				try {
					String appId = (String) jcomAppId.getSelectedItem();
					if (Objects.isNull(appId)) {
						ShowErrorMessage.show(String.format("请选择应用ID"));
						return;
					}
					
					List<EsbServiceidentify> protocols = importHandler.getPlatform().queryServiceidentify(appId);
					if (protocols.isEmpty()) {
						ShowErrorMessage.show(String.format("请到控制台为接入协议配置服务识别"));
						return;
					}
					
					jcomInProtocal.removeAllItems();
					for (int i = 0, len = protocols.size(); i < len; i++) {
						EsbServiceidentify protocol = protocols.get(i);
						jcomInProtocal.insertItemAt(protocol.getProtocolName(), i);
					}
				} catch (Exception e1) {
					LogUtils.error(e1.getMessage(), e1);
				}
			}
			
		}
		
		private void queryOutProtocal() {
			if (fill(jcomOutProtocal)) {
				try {
					String appId = (String) jcomAppId.getSelectedItem();
					if (Objects.isNull(appId)) {
						ShowErrorMessage.show(String.format("请选择应用ID"));
						return;
					}
					
					List<EsbProtocol> protocols = importHandler.getPlatform().queryProtocols(appId).stream().filter(p -> p.getProtocolAccessType().equals("c")).collect(Collectors.toList());
					if (protocols.isEmpty()) {
						ShowErrorMessage.show(String.format("请到控制台配置接出协议"));
						return;
					}
					
					jcomOutProtocal.removeAllItems();
					for (int i = 0, len = protocols.size(); i < len; i++) {
						EsbProtocol protocol = protocols.get(i);
						jcomOutProtocal.insertItemAt(protocol.getProtocolName(), i);
					}
				} catch (Exception e1) {
					LogUtils.error(e1.getMessage(), e1);
				}
			}
		}

		@Override
		public void actionPerformed(ActionEvent e) {
			jcomInProtocal.removeAllItems();
			jcomInProtocal.insertItemAt("选择接入协议...", 0);
			jcomInProtocal.setSelectedIndex(0);
			
			jcomOutProtocal.removeAllItems();
			jcomOutProtocal.insertItemAt("选择接出协议...", 0);
			jcomOutProtocal.setSelectedIndex(0);
			
			jcomFlows.removeAllItems();
			jcomFlows.insertItemAt("选择适配流程...", 0);
			jcomFlows.setSelectedIndex(0);
			
			try {
				importHandler.getPlatform().queryProtocols("").clear();
				importHandler.getPlatform().queryServiceidentify("").clear();
				importHandler.getPlatform().queryServiceFlow("").clear();
				LogUtils.log.setText("");
			} catch (Exception exp) {
				exp.printStackTrace();
			}
		}

	}
	
	private void queryFlows() {
		if (fill(jcomFlows)) {
			try {
				String appId = (String) jcomAppId.getSelectedItem();
				if (Objects.isNull(appId)) {
					ShowErrorMessage.show(String.format("请选择应用ID"));
					return;
				}
				
				List<EsbServiceFlow> flows = importHandler.getPlatform().queryServiceFlow(appId);
				if (flows.isEmpty()) {
					ShowErrorMessage.show(String.format("请到控制台配置适配流程"));
					return;
				}
				
				jcomFlows.removeAllItems();
				for (int i = 0, len = flows.size(); i < len; i++) {
					EsbServiceFlow flow = flows.get(i);
					jcomFlows.insertItemAt(flow.getFlowName(), i);
				}
			} catch (Exception e1) {
				LogUtils.error(e1.getMessage(), e1);
			}
		}
	}
	
	private boolean fill(JComboBox<String> jcom) {
		String desc = jcom.getItemAt(0);
		return desc.endsWith("...");
	}
	
	public enum MouseType {
		APPID, PROTOCAL, SERVICEDEFINED, FLOWS, CHANGEAPPID
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		// check choose action
		String appId = (String) jcomAppId.getSelectedItem();
		if (Objects.isNull(appId) || appId.endsWith("...")) {
			ShowErrorMessage.show(String.format("请选择应用ID"));
			return;
		}
		
		String inProtocal = (String) jcomInProtocal.getSelectedItem();
		if (Objects.isNull(inProtocal) || inProtocal.endsWith("...")) {
			ShowErrorMessage.show(String.format("请选择接入协议"));
			return;
		}
		
		String outProtocal = (String) jcomOutProtocal.getSelectedItem();
		if (Objects.isNull(outProtocal) || outProtocal.endsWith("...")) {
			ShowErrorMessage.show(String.format("请选择接出协议"));
			return;
		}
		
		String flow = (String) jcomFlows.getSelectedItem();
		if (Objects.isNull(flow) || flow.endsWith("...")) {
			ShowErrorMessage.show(String.format("请选择适配流程"));
			return;
		}
		
		try {
			EsbAppInfo _appInfo = importHandler.getPlatform().queryAppIds().stream().filter(a -> a.getServiceName().equals(appId)).findFirst().get();
			EsbProtocol _inProtocal = importHandler.getPlatform().queryProtocols(appId).stream().filter(p -> p.getProtocolName().equals(inProtocal)).findFirst().get();
			EsbServiceidentify serviceidentify = importHandler.getPlatform().queryServiceidentify(appId).stream().filter(s -> s.getProtocolName().equals(inProtocal)).findFirst().get();
			importHandler.getPlatform().setSelected(new EsbPublishSelect(_appInfo, _inProtocal, serviceidentify, outProtocal, flow));
		} catch (Exception e1) {
			LogUtils.error(e1.getMessage(), e1);
		}
		
		importHandler.actionPerformed(e);
	}

}
